<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">粗丝作业</text>
    </view>

    <!-- 出库信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">作业信息</text>
      </view>

      <!-- 出库类型标签页 -->
      <view class="info-form">
        <view class="form-item">
          <text class="form-label required">创建日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.currentDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.currentDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>

        <!-- 领料工序 -->
        <view class="form-item">
          <text class="form-label">当前工序</text>
          <view class="process-display">{{ formData.processName }}</view>
        </view>
        <view class="form-item">
          <text class="form-label">当前机组</text>
          <input
            id="prodCenterInput"
            class="form-input"
            v-model="formData.prodCenter"
            placeholder="请输入机组"
            @confirm="handleProdCenterConfirm"
            :focus="prodCenterFocus"
          />
          <button class="scan-btn align-right" @click="scanMachineCode">
            重置扫码
          </button>
        </view>
        <view class="form-item">
          <text class="form-label">班别</text>
          <view class="process-display">{{ formData.workClass }}</view>
        </view>
        <view class="form-item">
          <text class="form-label">班次</text>
          <view class="process-display">{{ formData.workShift }}</view>
        </view>
        <view class="form-item">
          <text class="form-label">操作备注</text>
          <input
            class="form-input"
            v-model="formData.remark"
            placeholder="请输入操作备注"
          />
        </view>
      </view>
    </view>

    <!-- 查询/选择区 -->
    <view class="material-section">
      <view class="section-header">
        <text class="section-title">日常作业</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'yesterday' }"
            @tap="handleTimeChange('yesterday')"
          >
            昨日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="handleTimeChange('today')"
          >
            今日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'tomorrow' }"
            @tap="handleTimeChange('tomorrow')"
          >
            明日
          </button>
        </view>
        <button class="scan-btn align-right" @click="testAndPrintBatch">
          测试打印
        </button>
      </view>
      <view class="tab-header">
        <button
          class="tab-btn"
          :class="{ active: activeTab === 'current' }"
          @click="activeTab = 'current'"
        >
          第1步：计划设定
        </button>
        <button
          class="tab-btn"
          :class="{ active: activeTab === 'selected' }"
          @click="activeTab = 'selected'"
        >
          第2步：工序作业
        </button>
      </view>
      <!-- 库存查询结果表格 -->
      <view class="material-table-section">
        <!-- 当前数据Tab -->
        <view v-if="activeTab === 'current'" class="tab-content">
          <view class="table-header">
            <text class="header-cell">计划日期</text>
            <text class="header-cell">标准</text>
            <text class="header-cell">钢种</text>
            <text class="header-cell">规格</text>
            <text class="header-cell">重量(KG)</text>
            <text class="header-cell">数量(件)</text>
            <text class="header-cell">操作</text>
          </view>

          <view v-for="item in dayBills" :key="item.id" class="table-row">
            <text class="table-cell">{{
              dateHelperApi.formatDate(item.ywDate)
            }}</text>
            <text class="table-cell">
              {{ item.standNo }}
            </text>
            <text class="table-cell">
              {{ item.steelGradeName }}
            </text>
            <text class="table-cell">
              {{ item.prodSpec }}
            </text>
            <text class="table-cell">
              {{ item.planCount }}
            </text>
            <text class="table-cell">
              {{ item.transCount }}
            </text>
            <button class="add-btn" @tap="storePlanInfo(item)">设定</button>
          </view>
        </view>
        <!-- 待出库数据Tab -->
        <view v-if="activeTab === 'selected'" class="tab-content">
          <!-- 表单布局 - 始终显示 -->
          <view class="plan-form-container">
            <view class="form-section">
              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">计划号</text>
                  <input
                    type="text"
                    class="modern-input"
                    v-model.trim="formData.planNo"
                  />
                </view>
                <view class="form-group">
                  <text class="form-label">批号</text>
                  <view class="input-with-button">
                    <input
                      type="text"
                      class="modern-input"
                      placeholder="请输入批号"
                      :focus="batchNoFocus"
                      v-model.trim="formData.batchNo"
                      @confirm="handleBatchNoConfirm"
                    />
                    <button
                      class="scan-btn weight-btn"
                      @tap="showBatchQueryModal"
                    >
                      查询
                    </button>
                  </view>
                </view>
              </view>

              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">钢种</text>
                  <input
                    type="text"
                    class="modern-input"
                    placeholder="当前钢种"
                    v-model.trim="formData.steelGradeName"
                  />
                </view>
                <view class="form-group">
                  <text class="form-label">炉号</text>
                  <input
                    type="text"
                    class="modern-input"
                    placeholder="炉号"
                    v-model.trim="formData.furnaceNo"
                    disabled
                    readonly
                  />
                </view>
              </view>

              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">当前规格</text>
                  <input
                    type="text"
                    class="modern-input"
                    placeholder="当前规格"
                    v-model.trim="formData.prodSpec"
                    disabled
                    readonly
                  />
                </view>
                <view class="form-group">
                  <text class="form-label">上料重量(KG)</text>
                  <view class="input-with-button">
                    <input
                      type="digit"
                      class="modern-input"
                      placeholder="请输入上料重量"
                      v-model.number="formData.prodCountOn"
                      @blur="validateNumber($event, formData, 'prodCountOn')"
                    />
                  </view>
                </view>
              </view>

              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">批次重量(KG)</text>
                  <view class="input-with-button">
                    <input
                      type="digit"
                      class="modern-input"
                      placeholder="请输入批次重量"
                      v-model.number="formData.qmAmount"
                      @blur="validateNumber($event, formData, 'qmAmount')"
                    />
                    <button class="scan-btn weight-btn" @tap="getWeight">
                      称重
                    </button>
                  </view>
                </view>
                <view class="form-group">
                  <text class="form-label">废品重量(KG)</text>
                  <view class="input-with-button">
                    <input
                      type="digit"
                      class="modern-input"
                      placeholder="请输入废品重量"
                      v-model.number="formData.scrapWg"
                      @blur="validateNumber($event, formData, 'scrapWg')"
                    />
                    <button class="scan-btn weight-btn" @tap="getWeight">
                      称重
                    </button>
                  </view>
                </view>
              </view>
              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">下线秤编码</text>
                  <input
                    type="text"
                    class="modern-input"
                    placeholder="点击批次称重获取"
                    v-model.trim="formData.wgEquipCodeBatch"
                  />
                </view>
                <view class="form-group">
                  <text class="form-label">废品秤编码</text>
                  <input
                    type="text"
                    class="modern-input"
                    placeholder="点击批次称重获取"
                    v-model.trim="formData.wgEquipCodeScrape"
                  />
                </view>
              </view>
              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">废品原因</text>
                  <input
                    type="text"
                    class="modern-input"
                    placeholder="请输入废品原因"
                    v-model.trim="formData.scrapReason"
                  />
                </view>
                <view class="form-group">
                  <!-- 这里可以添加另一个字段，或者留空保持对称 -->
                </view>
              </view>
              <!-- 按钮区 -->
              <view class="button-container">
                <view class="button-row">
                  <button class="scan-btn query-btn" @click="resetForm">
                    重置
                  </button>
                  <button class="scan-btn query-btn" @click="submitOnline">
                    上料
                  </button>
                  <button class="scan-btn query-btn" @click="submitScrap">
                    废品报废
                  </button>
                  <button class="scan-btn query-btn" @click="splitBatch">
                    拆批
                  </button>
                  <button class="scan-btn query-btn" @click="submitOffline">
                    下线
                  </button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!--创建成功后显示当前投料记录 -->
    <view class="material-section">
      <view class="section-header">
        <!-- 批号查询弹窗 -->
        <view
          v-if="showBatchQueryDialog"
          class="batch-query-modal"
          @tap="closeBatchQueryModal"
        >
          <view class="modal-content" @tap.stop="">
            <view class="modal-header">
              <text class="modal-title">批号查询</text>
              <button class="close-btn" @tap="closeBatchQueryModal">×</button>
            </view>

            <view class="modal-body">
              <!-- 查询表单 -->
              <view class="query-form">
                <input
                  type="text"
                  class="form-input"
                  placeholder="请输入批号进行模糊查询"
                  v-model.trim="batchQueryKeyword"
                  @confirm="executeBatchQuery"
                />
                <button
                  class="query-btn"
                  @tap="executeBatchQuery"
                  :disabled="batchQueryLoading"
                  :class="{ loading: batchQueryLoading }"
                >
                  {{ batchQueryLoading ? "查询中..." : "查询" }}
                </button>
              </view>
              <!-- 查询结果 -->
              <view
                class="query-results"
                v-if="batchSearchResults.length > 0 || batchQueryLoading"
              >
                <table class="result-table">
                  <thead class="table-header">
                    <tr>
                      <th>批号</th>
                      <th>炉号</th>
                      <th>钢种</th>
                      <th>规格</th>
                      <th>重量(KG)</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody class="table-body">
                    <tr
                      v-for="(item, index) in batchSearchResults"
                      :key="index"
                      class="table-row"
                    >
                      <td>{{ item.batchNo }}</td>
                      <td>{{ item.furnaceNo }}</td>
                      <td>{{ item.steelGradeName }}</td>
                      <td>{{ item.prodSpec }}</td>
                      <td>{{ item.weight || 0 }}</td>
                      <td>
                        <button
                          class="btn btn-primary"
                          @tap="selectBatchItem(item)"
                        >
                          选择
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </view>

              <!-- 无结果提示 -->
              <view
                v-if="
                  !batchQueryLoading &&
                  batchQueryKeyword &&
                  batchSearchResults.length === 0
                "
                class="empty-row"
              >
                暂无查询结果
              </view>
            </view>

            <view class="modal-footer">
              <button class="btn" @tap="closeBatchQueryModal">取消</button>
            </view>
          </view>
        </view>
        <text class="section-title">您今日的操作记录</text>
      </view>

      <!-- 记录类型标签页 -->
      <view class="tab-header">
        <button
          class="tab-btn"
          :class="{ active: recordActiveTab === 'feeding' }"
          @click="handleRecordTabChange('feeding')"
        >
          上料记录
        </button>
        <button
          class="tab-btn"
          :class="{ active: recordActiveTab === 'offline' }"
          @click="handleRecordTabChange('offline')"
        >
          下线记录
        </button>
        <button
          class="tab-btn"
          :class="{ active: recordActiveTab === 'scrap' }"
          @click="handleRecordTabChange('scrap')"
        >
          报废记录
        </button>
      </view>

      <view class="tab-content">
        <view class="table-header">
          <view class="header-cell">日期</view>
          <view class="header-cell">计划号</view>
          <view class="header-cell">批次</view>
          <view class="header-cell">钢种</view>
          <view class="header-cell">规格</view>
          <view class="header-cell">重量(KG)</view>
          <view class="header-cell">报废原因</view>
        </view>

        <view
          class="table-row"
          v-for="(item, index) in currentRecords"
          :key="index"
        >
          <view class="table-cell">{{
            item.ywDate ? dateHelperApi.formatDate(item.ywDate) : "-"
          }}</view>
          <view class="table-cell">{{ item.planNo || "-" }}</view>
          <view class="table-cell">{{ item.batchNo || "-" }}</view>
          <view class="table-cell">{{ item.steelGradeName || "-" }}</view>
          <view class="table-cell">{{ item.prodSpec || "-" }}</view>
          <view class="table-cell">{{ item.qmAmount || 0 }}</view>
          <view class="table-cell">{{ item.scrapReason || "-" }}</view>
        </view>

        <!-- 无数据提示 -->
        <view v-if="currentRecords.length === 0" class="empty-tip">
          <text>暂无{{ getRecordTabName }}记录</text>
        </view>
      </view>
    </view>
    
    <!-- 隐藏的canvas元素，用于条码打印 -->
    <canvas 
      canvas-id="printQRCanvas" 
      style="width: 384px; height: 200px; position: fixed; left: -9999px; top: -9999px; visibility: hidden;"
      :style="{ width: '384px', height: '200px' }"
    ></canvas>
  </view>
</template>

<script>
import { dateHelperApi } from "@/pages/smart/utils/date-helper";
import { recordMethods } from "./recordMethods";
export default {
  data() {
    return {
      // 临时计划项（用于selectedTable为空时的编辑）
      _tempPlanItem: null,

      // 当前激活的标签页
      activeTab: "current",

      // 炉批记录标签页
      recordActiveTab: "feeding", // feeding: 上料记录, offline: 下线记录, scrap: 报废记录

      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        outType: "三相",
        warehouseCode: "",
        warehouseName: "",
        processName: "",
        prodCenter: "", // 机组
        workShift: "", // 班次
        workClass: "", // 班组
        nickName: "", // 姓名
        // 新增10项
        furnaceBegin: "",
        furnaceEnd: "",
        furnaceTareWg: 0,
        furnaceCostWg: 0,
        furnaceOutWg: 0,
        arBlowCost: 0,
        qaCount: 0,
        qaWg: 0,
        scrapCount: 0,
        scrapWg: 0,
        scrapReason: "",
        // 新增字段：计划号、批号、钢种、炉号、规格、件次重量、上料重量
        planNo: "", // 计划号
        batchNo: "", // 批号
        steelGradeName: "", // 钢种
        furnaceNo: "", // 炉号
        prodSpec: "", // 当前规格
        qmAmount: 0, // 件次重量
        prodCountOn: 0, // 上料重量
        wgEquipCodeBatch: "", // 计量秤编码
        wgEquipCodeScrape: "", // 计量秤编码
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },

      // 当前工序信息
      currentProcess: {
        processName: "",
      },

      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
        customerName: "",
      },

      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 库存表格数据
      currentTable: [],

      // 待出库表格数据
      selectedTable: [],

      // 选中行
      selectedRows: [],

      // 加载状态
      loading: false,

      // 表单重构新增数据
      // 当前计划索引
      currentPlanIndex: 0,

      // 数据源（预留）
      standards: [], // 标准列表
      steelGrades: [], // 钢种列表
      specs: [], // 规格列表
      dayBills: [], // 炉次日账单列表
      planNoIndex: 0, // 当前选中的炉批下标

      // 批号查询相关
      batchSearchResults: [], // 批号查询结果
      showBatchDropdown: false, // 是否显示批号下拉列表
      batchNoFocus: false, // 批次号输入框聚焦状态
      showBatchQueryDialog: false, // 是否显示批号查询弹窗
      batchQueryKeyword: "", // 批号查询关键词
      batchQueryLoading: false, // 批号查询加载状态

      // 三种记录类型的数据
      feedingRecords: [], // 上料记录
      offlineRecords: [], // 下线记录
      scrapRecords: [], // 报废记录

      // 机组输入框聚焦状态
      prodCenterFocus: false,
      
      // 打印机设备状态
      printerDevice: {
        deviceId: '',
        connected: false,
        name: '',
        serviceId: '',
        characteristicId: ''
      },
    };
  },

  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },

    // 是否可以提交
    canSubmit() {
      return this.selectedTable.length > 0;
    },

    // 总数量
    totalCount() {
      return this.selectedTable.reduce(
        (sum, item) => sum + (Number(item.outTransCount) || 0),
        0
      );
    },

    // 总重量
    totalWeight() {
      return this.selectedTable.reduce(
        (sum, item) => sum + (Number(item.outProdCount) || 0),
        0
      );
    },

    // 当前计划项
    currentPlanItem() {
      // 如果selectedTable中有数据，返回对应项
      if (
        this.selectedTable.length > 0 &&
        this.selectedTable[this.currentPlanIndex]
      ) {
        return this.selectedTable[this.currentPlanIndex];
      }

      // 如果selectedTable为空，返回临时对象用于编辑
      // 使用Vue的响应式数据存储临时对象
      if (!this._tempPlanItem) {
        this._tempPlanItem = {
          planDate: new Date(this.formData.currentDate + "T00:00:00").getTime(),
          standNo: "",
          steelGradeName: "",
          prodSpec: "",
          ProdCount: 0,
          TransCount: 0,
          standIndex: -1,
          steelGradeIndex: -1,
          specIndex: -1,
        };
      }
      return this._tempPlanItem;
    },

    // 当前显示的记录列表
    currentRecords() {
      switch (this.recordActiveTab) {
        case "feeding":
          return this.feedingRecords;
        case "offline":
          return this.offlineRecords;
        case "scrap":
          return this.scrapRecords;
        default:
          return [];
      }
    },

    // 获取当前记录标签名称
    getRecordTabName() {
      switch (this.recordActiveTab) {
        case "feeding":
          return "上料";
        case "offline":
          return "下线";
        case "scrap":
          return "报废";
        default:
          return "";
      }
    },

    // 是否可以提交当前计划
    canSubmitCurrentPlan() {
      const item = this.currentPlanItem;
      return (
        item &&
        item.ProdCount !== null &&
        item.ProdCount !== undefined &&
        item.ProdCount !== "" &&
        item.TransCount !== null &&
        item.TransCount !== undefined &&
        item.TransCount !== ""
      );
    },

    // 上料按钮可用状态
    canSubmitOnline() {
      // 基础条件：有选中记录且表单数据完整
      if (
        !this.formData.batchNo ||
        !this.formData.steelGradeName ||
        !this.formData.prodSpec
      ) {
        return false;
      }

      // 重量必须大于0
      const weight = Number(this.formData.prodCountOn);
      if (!weight || weight <= 0 || isNaN(weight)) {
        return false;
      }

      // 必须选择计划日期
      if (!this.formData.currentDate) {
        return false;
      }

      return true;
    },

    // 废品报废按钮可用状态
    canSubmitScrap() {
      // 基础条件：有选中记录
      if (!this.formData.batchNo) {
        return false;
      }

      // 必须有报废原因
      if (
        !this.formData.scrapReason ||
        this.formData.scrapReason.trim() === ""
      ) {
        return false;
      }

      // 报废重量必须大于0
      const scrapWeight = Number(this.formData.scrapWg);
      if (!scrapWeight || scrapWeight <= 0 || isNaN(scrapWeight)) {
        return false;
      }

      return true;
    },

    // 下线按钮可用状态
    canSubmitOffline() {
      // 基础条件：有选中记录且表单数据完整
      if (
        !this.formData.batchNo ||
        !this.formData.steelGradeName ||
        !this.formData.prodSpec
      ) {
        return false;
      }

      // 下线重量必须大于0
      const offlineWeight = Number(this.formData.qmAmount);
      if (!offlineWeight || offlineWeight <= 0 || isNaN(offlineWeight)) {
        return false;
      }

      // 必须选择计划日期
      if (!this.formData.currentDate) {
        return false;
      }

      return true;
    },
  },

  async onLoad() {
    console.log("页面加载开始...");

    //加载缓存的工序、机组、班次、班组
    const userConfig = this.$store.state.user.userConfig;
    const nickname = this.$store.state.user.nickname;
    this.formData.processName = userConfig.processName || "";
    this.formData.prodCenter = userConfig.prodCenter || "";
    this.formData.workShift = userConfig.workShift || "";
    this.formData.workClass = userConfig.workClass || "";
    this.formData.nickName = nickname || "";

    try {
      // 初始化默认时间范围（今日）
      console.log("初始化默认时间范围...");
      this.handleTimeChange("today");

      // 等待时间初始化完成后再加载其他数据
      console.log("时间初始化完成，开始加载其他数据...");
      await this.initData();

      console.log("所有数据初始化完成");
    } catch (error) {
      console.error("初始化失败:", error);
      uni.showToast({
        title: "页面初始化失败",
        icon: "error",
      });
    }

    // 页面加载完成后聚焦到机组输入框
    this.$nextTick(() => {
      setTimeout(() => {
        this.focusProdCenterInput();
      }, 500); // 延迟500ms确保页面完全渲染
    });
  },

  onBackPress() {
    if (this.selectedTable.length > 0) {
      uni.showModal({
        title: "提示",
        content: "有未提交数据，确认退出当前页面吗？",
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          }
        },
      });
      return true;
    }
  },

  methods: recordMethods,
};
</script>
<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";
</style>
